#include "Thread.hpp"
#include <vector>

using namespace ThreadModule;
#include "Lock.hpp"
int g_tick = 10000;
class ThreadData
{
public:
    ThreadData(int& tick,const std::string& name,pthread_mutex_t& mutex)
    :_tick(tick),_name(name),_total(0),_mutex(mutex)
    {}
    ~ThreadData()
    {}
public:
    int &_tick;
    std::string _name;
    int _total;
    pthread_mutex_t &_mutex;
};
//3.RAII风格的加锁、解锁
void route(ThreadData* td)
{
    while(1)
    {
        //在循环内创建一个类 临时对象，出循环销毁，调用析构函数，同时解锁
        Lock lock(&td->_mutex);
        if(td->_tick>0)
        {
            usleep(1000);
            printf("%s running,can get only tick:%d\n",td->_name.c_str(),td->_tick);
            td->_tick--;
            td->_total++;
        }
        else{
           
            break;
        }

    }
}
// //2.main函数定义了局部锁
// void route(ThreadData* td)
// {
//     while(1)
//     {
//         pthread_mutex_lock(&td->_mutex);
//         if(td->_tick>0)
//         {
//             usleep(1000);
//             printf("%s running,can get only tick:%d\n",td->_name.c_str(),td->_tick);
//             td->_tick--;
//             pthread_mutex_unlock(&td->_mutex);
//             td->_total++;
//         }
//         else{
//             pthread_mutex_unlock(&td->_mutex);

//             break;
//         }

//     }
// }
// //1.定义全局互斥锁
// pthread_mutex_t g_mutex= PTHREAD_MUTEX_INITIALIZER;
// void route(ThreadData* td)
// {
//     while(1)
//     {
//         pthread_mutex_lock(&g_mutex);
//         if(td->_tick>0)
//         {
//             usleep(1000);
//             printf("%s running,can get only tick:%d\n",td->_name.c_str(),td->_tick);
//             td->_tick--;
//             pthread_mutex_unlock(&g_mutex);
//             td->_total++;
//         }
//         else{
//             pthread_mutex_unlock(&g_mutex);

//             break;
//         }

//     }

// }
const int num = 4;
int main()
{
    //局部锁
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);


    std::vector<Thread<ThreadData*>> threads;

    std::vector<ThreadData*> datas;

    //1.创建一批线程
    for(int i = 0;i < num;++i)
    {
        std::string name = "thread-" + std::to_string(i+1);
        ThreadData* td = new ThreadData(g_tick,name,mutex);
        threads.emplace_back(route,td,name);
        datas.emplace_back(td);
    }

    //2.启动一批线程
    for(auto & thread:threads)
    {
        thread.Start();
    }

    //3等待一批线程
    for(auto& thread:threads)
    {
        thread.Join();
    }

    sleep(1);
    //4.输出数据
    for(auto & data:datas)
    {
        std::cout << data->_name << "get tick:"<<data->_total<<std::endl;
        delete data;
    }

    pthread_mutex_destroy(&mutex);
    return 0;
}